<!-- src/views/forum/detail.vue -->
<template>
  <div class="post-detail-container" v-loading="loading">
    <!-- 帖子内容 -->
    <div v-if="post" class="post-content">
      <div class="post-header">
        <h1 class="post-title">{{ post.title }}</h1>
        <div class="post-meta">
          <span>发帖人: {{ post.userName }}</span>
          <span class="meta-divider">|</span>
          <span>发布时间: {{ formatDate(post.createTime) }}</span>

          <div class="post-actions" v-if="canDelete(post.userId)">
            <el-button type="text" @click="handleDeletePost" class="delete-btn"
              >删除帖子</el-button
            >
          </div>
        </div>
      </div>

      <div class="post-body">
        <p class="post-text">{{ post.content }}</p>
      </div>

      <!-- 回复列表 -->
      <div class="reply-section">
        <h3>回复列表 ({{ total || 0 }})</h3>

        <div v-if="replyList.length === 0" class="no-replies">
          暂无回复，来发表第一条回复吧
        </div>

        <div v-else class="reply-list">
          <div
            v-for="(reply, index) in replyList"
            :key="reply.id"
            class="reply-item"
          >
            <div class="reply-header">
              <span class="reply-author">{{ reply.userName }}</span>
              <span class="reply-time">{{ formatDate(reply.createTime) }}</span>

              <div class="reply-actions" v-if="canDelete(reply.userId)">
                <el-button
                  type="text"
                  @click="handleDeleteReply(reply)"
                  class="delete-btn"
                  >删除</el-button
                >
              </div>
            </div>

            <div class="reply-content">
              <p>{{ reply.content }}</p>
            </div>

            <el-divider v-if="index < replyList.length - 1"></el-divider>
          </div>
        </div>

        <!-- 回复分页 -->
        <div class="pagination-container" v-if="total > pageSize">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageIndex"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>

      <!-- 发表回复 -->
      <div class="add-reply-section">
        <h3>发表回复</h3>
        <el-form :model="replyForm" :rules="replyRules" ref="replyForm">
          <el-form-item prop="content">
            <el-input
              type="textarea"
              v-model="replyForm.content"
              placeholder="请输入回复内容（5-500个字符）"
              :rows="4"
              maxlength="500"
              show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitReply" :loading="submitting"
              >发表回复</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div v-else-if="!loading" class="post-not-found">
      <el-empty description="帖子不存在或已被删除">
        <el-button type="primary" @click="goBack">返回论坛</el-button>
      </el-empty>
    </div>

    <!-- 返回按钮 -->
    <div class="back-container">
      <el-button icon="el-icon-back" @click="goBack">返回论坛</el-button>
    </div>
  </div>
</template>

<script>
import forumApi from "@/api/forum";
import { mapState } from "vuex";

export default {
  name: "PostDetail",
  data() {
    return {
      loading: true,
      submitting: false,
      postId: null,
      post: null,
      replyList: [],
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      replyForm: {
        postId: "",
        content: "",
        userId: "",
      },
      replyRules: {
        content: [
          { required: true, message: "请输入回复内容", trigger: "blur" },
          {
            min: 5,
            max: 500,
            message: "回复内容长度在5到500个字符之间",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  created() {
    if (this.checkUserProfile()) {
      this.postId = this.$route.query.id;
      if (!this.postId) {
        this.$message.error("帖子ID不存在");
        this.goBack();
        return;
      }

      this.replyForm.postId = this.postId;
      this.replyForm.userId = this.userInfo.id;

      this.fetchPostDetail();
      this.fetchReplies();
    }
  },
  methods: {
    checkUserProfile() {
      if (!this.userInfo || !this.userInfo.id) {
        this.$message.error("请先登录");
        this.$router.push("/login");
        return false;
      }
      return true;
    },
    // 获取帖子详情
    fetchPostDetail() {
      this.loading = true;

      // 使用getPostPage API并找到对应ID的帖子
      // 注意: 这里是一个变通方法，因为后端没有提供获取单个帖子的API
      forumApi
        .getPostPage({
          pageIndex: 1,
          pageSize: 100, // 获取足够多的帖子，希望能找到目标帖子
        })
        .then((res) => {
          if (res.code === 1 && res.response && res.response.list) {
            const foundPost = res.response.list.find(
              (post) =>
                post.id === this.postId || post.id === parseInt(this.postId)
            );
            if (foundPost) {
              this.post = foundPost;
            } else {
              this.$message.error("找不到该帖子");
            }
          } else {
            this.$message.error(res.message || "获取帖子详情失败");
          }
        })
        .catch((error) => {
          console.error("获取帖子详情失败:", error);
          this.$message.error("获取帖子详情失败");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取回复列表
    fetchReplies() {
      forumApi
        .getReplyPage({
          postId: this.postId,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        })
        .then((res) => {
          if (res.code === 1) {
            this.replyList = res.response.list || [];
            this.total = res.response.total || 0;
          } else {
            this.$message.error(res.message || "获取回复列表失败");
          }
        })
        .catch((error) => {
          console.error("获取回复列表失败:", error);
          this.$message.error("获取回复列表失败");
        });
    },
    // 提交回复
    submitReply() {
      this.$refs.replyForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        this.submitting = true;
        forumApi
          .createReply(this.replyForm)
          .then((res) => {
            if (res.code === 1) {
              this.$message.success("回复成功");
              this.replyForm.content = "";
              this.fetchReplies(); // 刷新回复列表
            } else {
              this.$message.error(res.message || "回复失败");
            }
          })
          .catch((error) => {
            console.error("回复失败:", error);
            this.$message.error("回复失败，请稍后重试");
          })
          .finally(() => {
            this.submitting = false;
          });
      });
    },
    // 删除帖子
    handleDeletePost() {
      this.$confirm("确定要删除这个帖子吗? 删除后将无法恢复", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          forumApi
            .deletePost(this.post.id, this.userInfo.id, this.userInfo.role)
            .then((res) => {
              if (res.code === 1) {
                this.$message.success("删除成功");
                this.goBack();
              } else {
                this.$message.error(res.message || "删除失败");
              }
            })
            .catch((error) => {
              console.error("删除帖子失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          // 取消删除操作
        });
    },
    // 删除回复
    handleDeleteReply(reply) {
      this.$confirm("确定要删除这条回复吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          forumApi
            .deleteReply(reply.id, this.userInfo.id, this.userInfo.role)
            .then((res) => {
              if (res.code === 1) {
                this.$message.success("删除成功");
                this.fetchReplies(); // 刷新回复列表
              } else {
                this.$message.error(res.message || "删除失败");
              }
            })
            .catch((error) => {
              console.error("删除回复失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          // 取消删除操作
        });
    },
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return "";
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
        2,
        "0"
      )}-${String(date.getDate()).padStart(2, "0")} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },
    // 检查是否有删除权限
    canDelete (itemUserId) {
      // 管理员(role=3)或自己发的可以删除
      return (
        this.userInfo &&
        (this.userInfo.id === itemUserId || this.userInfo.role === 3)
      );
    },
    // 返回论坛列表
    goBack () {
      this.$router.push("/forum/index");
    },
    // 页码变化
    handleCurrentChange (val) {
      this.pageIndex = val
      this.fetchReplies()
    },
    // 每页条数变化
    handleSizeChange (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.fetchReplies()
    },
  },
};
</script>

<style scoped>
.post-detail-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  max-width: 1000px;
  margin: 0 auto;
  position: relative;
}

.post-content {
  margin-bottom: 30px;
}

.post-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.post-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.post-meta {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.meta-divider {
  margin: 0 10px;
}

.post-actions {
  margin-left: auto;
}

.post-body {
  margin-bottom: 40px;
}

.post-text {
  font-size: 16px;
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
}

.reply-section {
  margin-bottom: 40px;
}

.no-replies {
  padding: 20px;
  text-align: center;
  color: #909399;
  background: #f5f7fa;
  border-radius: 4px;
}

.reply-list {
  margin-top: 20px;
}

.reply-item {
  padding: 15px 0;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.reply-author {
  font-weight: bold;
  color: #409eff;
}

.reply-time {
  margin-left: 15px;
  color: #909399;
  font-size: 13px;
}

.reply-actions {
  margin-left: auto;
}

.reply-content {
  margin-left: 0;
  font-size: 14px;
  line-height: 1.6;
}

.add-reply-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.delete-btn {
  color: #f56c6c;
}

.back-container {
  margin-top: 20px;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}

.post-not-found {
  text-align: center;
  padding: 60px 0;
}
</style>
